package com.qdlc.p2p.quartz;

import java.util.Calendar;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.qdlc.p2p.biz.task.impl.MailUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
/**
 */
public abstract class AbstractJob implements Job {

    protected static Logger logger = Logger.getLogger("job");

    private  static Calendar cale;
    static {
        cale = Calendar.getInstance();
    }

    @Override
    public void execute(final JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String className = this.getClass().getSimpleName();
        cale.setTimeInMillis(System.currentTimeMillis());
        logger.info(className + " begin at " + DateUtil.dateStr4(cale.getTime()));
        try {
            process();
        } catch (Exception ex) {
            ex.printStackTrace();
            MailUtil.sendMail("定时器" + className + "出错", ex);
        } finally {
            String configName = getConfigName();
            if (QuartzConfigManager.isChanged(configName)) {
                try {
                    String cron = (String) QuartzConfigManager.getVal(configName);
                    if (StringUtil.isNotEmpty(cron)) {

                        QuartzManage.modifyJobTime(jobExecutionContext, cron);
                        QuartzConfigManager.setChanged(configName, false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    MailUtil.sendMail("modify job execute time ".concat(className).concat(" error"), e);
                }
            }
        }
        logger.info(className + " execute time " + (System.currentTimeMillis() - cale.getTimeInMillis()));
        cale.setTimeInMillis(System.currentTimeMillis());
        logger.info(className + " end at " + DateUtil.dateStr4(cale.getTime()));
    }

    protected abstract void process() throws Exception;

    protected String getConfigName() {
        String className = this.getClass().getSimpleName();
        String configName = className.substring(0, 1).toLowerCase() + className.substring(1) + ".cronExpression";
        return configName;
    }
}
